package com.tbit.uqbike.client.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * @author Kang
 * @date 2017年12月21日下午3:38:33
 * @description :http调用第三方接口工具类
 */
@Slf4j
public class HttpClientUtils {
    private final static Object syncLock = new Object();
    private static final String ENCODING = "UTF-8";
    private static PoolingHttpClientConnectionManager clientConnectionManager = null;
    private static RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setSocketTimeout(10000).setConnectTimeout(10000).build();
    private static volatile CloseableHttpClient httpClient = null;

    /**
     * 初始化连接
     */
    static {
        try {
            SSLContext sslContext = SSLContexts
                    .custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslsf).register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
            clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            clientConnectionManager.setMaxTotal(50);
            clientConnectionManager.setDefaultMaxPerRoute(25);
        } catch (Exception e) {
        }
    }

    /**
     * 设置请求头信息
     *
     * @param headers
     * @param request
     * @return
     */
    private static HttpRequest setHeaders(Map<String, Object> headers, HttpRequest request) {
        for (Map.Entry entry : headers.entrySet()) {
            if (!"Cookie".equals(entry.getKey())) {
                request.addHeader((String) entry.getKey(), (String) entry.getValue());
            } else {
                Map<String, Object> Cookies = (Map<String, Object>) entry.getValue();
                for (Map.Entry entry1 : Cookies.entrySet()) {
                    request.addHeader(new BasicHeader("Cookie", (String) entry1.getValue()));
                }
            }
        }
        return request;
    }

    public static CloseableHttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    CookieStore cookieStore = new BasicCookieStore();
                    BasicClientCookie cookie = new BasicClientCookie("sessionID", "######");
                    cookie.setDomain("#####");
                    cookie.setPath("/");
                    cookieStore.addCookie(cookie);
                    httpClient = HttpClients.custom().setConnectionManager(clientConnectionManager)
                            .setDefaultCookieStore(cookieStore).setDefaultRequestConfig(config).build();
                }
            }
        }
        return httpClient;
    }

    /**
     * post表单请求
     *
     * @param url
     * @param headers
     * @param data
     * @return
     */
    public static String httpPost(String url, Map<String, Object> headers, List<NameValuePair> data) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest request = new HttpPost(url);
        if (headers != null && !headers.isEmpty()) {
            request = setHeaders(headers, request);
        }
        CloseableHttpResponse response = null;
        UrlEncodedFormEntity uefEntity;
        try {
            HttpPost httpPost = (HttpPost) request;
            uefEntity = new UrlEncodedFormEntity(data, "UTF-8");

            httpPost.setEntity(uefEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("httpPost请求超时！", e);
            log.error(e.getMessage(), e);

        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static String httpGet(String url, Map<String, Object> headers) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest httpGet = new HttpGet(url);
        if (headers != null && !headers.isEmpty()) {
            httpGet = setHeaders(headers, httpGet);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute((HttpGet) httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("httpGet请求超时！" + url);
            log.error(e.getMessage(), e);

        }
        return null;
    }

    /**
     * json格式数据提交
     *
     * @param url
     * @param json
     * @throws IOException
     */
    public static String httpJson(String url, String json) throws IOException {
        final String CONTENT_TYPE_TEXT_JSON = "text/json";
        CloseableHttpClient httpClient = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");

        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        CloseableHttpResponse response2 = null;
        response2 = httpClient.execute(httpPost);
        HttpEntity entity2 = null;
        entity2 = response2.getEntity();
        String s2 = EntityUtils.toString(entity2, "UTF-8");

        return s2;

    }

    /**
     * post 表单提交
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public static String httpPost(String url, Map<String, String> paramsMap) {
        return send(RequestBuilder.post(url), paramsMap);
    }

    /**
     * 发送请求
     *
     * @param requestBuilder
     * @param paramsMap
     * @return
     */
    public static String send(RequestBuilder requestBuilder, Map<String, String> paramsMap) {
        CloseableHttpClient client = getHttpClient();
        requestBuilder.setCharset(Charset.forName(ENCODING));
        String responseText = "";

        if (paramsMap != null) {
            for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                requestBuilder.addParameter(param.getKey(), param.getValue());
            }

            CloseableHttpResponse response = null;
            try {
                response = client.execute(requestBuilder.build());
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        responseText = EntityUtils.toString(entity, ENCODING);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);//正式项目中请改为log打印
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);//正式项目中请改为log打印
                }
            }

        }
        return responseText;
    }


    public static void main(String[] args) throws IOException {

        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("content","hello world");
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("text",jsonObject);
        jsonObject1.put("msgtype","text");
        String url= "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=694cf5d5-a39c-4755-9dbe-dd844baac442";
        httpJson(url,jsonObject1.toJSONString());*/
        Integer mileage = 3654;
        double mileageDB = (double) mileage / 1000;
        System.out.println(mileageDB);

    }

}
